//
//  YZZBHtmlViewController.m
//  NightPlay
//
//  Created by liufy on 2017/3/23.
//  Copyright © 2017年 liufy. All rights reserved.
//

#import "YZZBHtmlViewController.h"
#import <WebKit/WebKit.h>

@interface YZZBHtmlViewController ()<WKNavigationDelegate>

@property (nonatomic,weak) CALayer *progresslayer;

@property (nonatomic,weak) WKWebView *webView;

@property (nonatomic, assign) BOOL isNavigationBarHidden;

@property (nonatomic, copy) NSArray *webImageArr;

@end

@implementation YZZBHtmlViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if(!_pathString ){
        UIBarButtonItem *retweet = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"transparentMore"] style:UIBarButtonItemStyleDone target:self action:@selector(retweet:)];
        self.navigationItem.rightBarButtonItem = retweet;
    }
    
    if(_hideShareBtn)self.navigationItem.rightBarButtonItem = nil;
    
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [self.view addSubview:webView];
    webView.navigationDelegate = self;
    self.webView = webView;
    //添加进度属性监听
    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
    //进度条
    UIView *progress = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 3)];
    progress.backgroundColor = [UIColor clearColor];
    [self.view addSubview:progress];
    
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake(0, 0, 0, 3);
    layer.backgroundColor = YZSubColor.CGColor;
    [progress.layer addSublayer:layer];
    self.progresslayer = layer;
    
    if(self.urlString){
        if ([self.urlString rangeOfString:@"http"].location == NSNotFound) {
            self.urlString = [NSString stringWithFormat:@"https://%@",self.urlString];
        }
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];
    }else if (self.pathString){
        NSURL *pathURL = [[NSBundle mainBundle] URLForResource:self.pathString withExtension:@"html"];
        [self.webView loadRequest:[NSURLRequest requestWithURL:pathURL]];
    }
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _isNavigationBarHidden = self.navigationController.navigationBar.isHidden;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = _isNavigationBarHidden;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
//        DLog(@"%@", change);
        self.progresslayer.opacity = 1;
        self.progresslayer.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[NSKeyValueChangeNewKey] floatValue], 3);
        if ([change[NSKeyValueChangeNewKey] floatValue] == 1) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progresslayer.opacity = 0;
            });
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progresslayer.frame = CGRectMake(0, 0, 0, 3);
            });
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    var imgScr = '';\
    for(var i=0;i<objs.length;i++){\
    imgScr = imgScr + objs[i].src + '+';\
    };\
    return imgScr;\
    };";
    
    WEAK_SELF(weakSelf)
    [webView evaluateJavaScript:jsGetImages completionHandler:nil];
    [webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        
        NSArray *urlArray = [NSMutableArray arrayWithArray:[result componentsSeparatedByString:@"+"]];
        //urlResurlt 就是获取到得所有图片的url的拼接；mUrlArray就是所有Url的数组
        weakSelf.webImageArr = urlArray;
    }];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    self.navigationItem.rightBarButtonItem = nil;
}

#pragma mark -- retweet
- (void)retweet:(UIBarButtonItem *)sender{
//    
//    //1、创建分享参数
//    NSArray* imageArray = _webImageArr.count != 0 ? @[_webImageArr.firstObject] :
//  @[@"http://bucket-user-avatar.nos-eastchina1.126.net/app_logo.png"];
//    // （注意：图片必须要在Xcode左边目录里面，名称必须要传正确，如果要分享网络图片，可以这样传iamge参数 images:@[@"http://mob.com/Assets/images/logo.png?v=20150320"]）
//    
//    NSString *titleHtmlInfo = self.webView.title;
//    NSString *title = titleHtmlInfo;
//    NSString *description = @"Ta向你分享了夜站直播潮酷资讯，快点击查看吧！";
//    NSString *url = self.urlString;
//    
//    [YYShareSDKTool shareContentWithShareContentType:SSDKContentTypeAuto contentTitle:title contentDescription:description contentImage:imageArray contentURL:url showInView:nil success:nil failure:nil OtherResponseStatus:nil];
}


- (void)dealloc{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

@end
